package com.caissa.framework.starter.autoconfigure.reference;

import com.caissa.framework.starter.autoconfigure.common.CatContext;
import com.caissa.framework.starter.autoconfigure.common.CatHttpConstants;
import com.dianping.cat.Cat;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

import static com.dianping.cat.CatConstants.CAISSA_CAT_DOMAIN;

/**
 *
 * feignclient 拦截注入trace info
 *
 * @auther wangwei
 * @date 2020/8/24
 */
@Slf4j
public class CatFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {

        try {
            Cat.Context ctx = new CatContext();
            Cat.logRemoteCallClient(ctx, template.feignTarget().name());
            template.header(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID, ctx.getProperty(Cat.Context.ROOT));
            template.header(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID, ctx.getProperty(Cat.Context.PARENT));
            template.header(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID, ctx.getProperty(Cat.Context.CHILD));

            //本地ip
            template.header(CatHttpConstants.CAT_HTTP_HEADER_CLIENT_IP, NetworkInterfaceManager.INSTANCE.getLocalHostAddress());
            //服务名
            template.header(CatHttpConstants.CAT_HTTP_HEADER_CLIENT_APPNAME, System.getProperty(CAISSA_CAT_DOMAIN));
        } catch (Exception e) {
            log.error("传递trace info报错",e);
        }
    }
}
